package com.erp.gather.controller;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.gather.domain.bo.ErpSellerStoreProductBo;
import com.erp.gather.domain.vo.ErpSellerStoreProductVo;
import com.erp.gather.mapper.ErpSellerStoreProductExpandMapper;
import com.erp.gather.service.IErpSellerStoreProductService;
import com.ruoyi.auto.api.RemoteAutoSellerStoreService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.gather.api.domain.ErpSellerStoreProductExpand;
import com.ruoyi.gather.api.domain.dto.PublishInnerAuthDto;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
 *
 * @author erp
 * @date 2023-03-28
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/seller/sellerStoreProduct")
public class ErpSellerStoreProductController extends BaseController {
    // redisson分布式锁的key
    private static final String LOCK_TEST_KEY = "redisson:lock:publish";

    private final IErpSellerStoreProductService iErpSellerStoreProductService;
    private final ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Resource
    RemoteAutoSellerStoreService remoteAutoSellerStoreService;
//	/**
//	 * 查询商品交易表现
//	 */
//	@GetMapping("/queryProductBusinessInfoById")
//	public R<Object> queryProductBusinessInfoById(Long productId) {
//		return iErpSellerStoreProductService.queryProductBusinessInfoById(productId);
//	}
//
//	/**
//	 * 查看商品审核状态
//	 */
//	@GetMapping("/findAeProductStatusById")
//	public R<Object> findAeProductStatusById(Long productId) {
//		return iErpSellerStoreProductService.findAeProductStatusById(productId);
//	}

    /**
     * 查询商品的规格
     */
    @GetMapping("/getSkuNameById")
    public R<List<Map<String, Object>>> getSkuNameById(Long id) {
        List<Map<String, Object>> list = iErpSellerStoreProductService.getSkuNameById(id);
        return R.ok(list);
    }

    /**
     * 查询卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @GetMapping("/list")
    public TableDataInfo<ErpSellerStoreProductVo> list(ErpSellerStoreProductBo bo, PageQuery pageQuery) {
        return iErpSellerStoreProductService.queryPageList(bo, pageQuery);
    }


    /**
     * 获取卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<ErpSellerStoreProductVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(iErpSellerStoreProductService.queryById(id));
    }

    @GetMapping("getSellerStoreProductInfoById/{id}")
    public R<Object> getSellerStoreProductInfoById(@PathVariable("id") String id) {
        return iErpSellerStoreProductService.getSellerStoreProductInfoById(id);
    }

    /**
     * 新增卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Log(title = "卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ErpSellerStoreProductBo bo) {
        return toAjax(iErpSellerStoreProductService.insertByBo(bo));
    }

    /**
     * 修改卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Log(title = "卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpSellerStoreProductBo bo) {
        return toAjax(iErpSellerStoreProductService.updateByBo(bo));
    }

    /**
     * 删除卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     *
     * @param ids 主键串
     */
    @Log(title = "卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(iErpSellerStoreProductService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 发布商品到速卖通
     *
     * @return
     */
    @PostMapping("/publish")
    public R<Object> publish(String sellerProductIds,
                             Long storeId,
                             Long skuStock,
                             ErpSellerStoreProductExpand erpSellerStoreProductExpand) {
        return iErpSellerStoreProductService.publish(sellerProductIds, storeId, skuStock, erpSellerStoreProductExpand);
    }

    /**
     * 发布商品到速卖通
     *
     * @return
     */
    @PostMapping("/publishChoiceProduct")
    public R<Object> publishChoiceProduct(Long sellerProductId,
                             Long storeId,
                             Long stock,
                             String brandId,
                             String templateld) {
        return iErpSellerStoreProductService.publishChoiceProduct(sellerProductId, storeId, stock, brandId,templateld);
    }

    /**
     * 裂变
     *
     * @return
     */
    @GetMapping("/fission")
    public R<Object> fission(Long sellerStoreProductId) {
        return iErpSellerStoreProductService.fission(sellerStoreProductId);
    }

    /**
     * 重新上架
     *
     * @param sellerStoreProductId
     * @return
     */
    @GetMapping("/restartpublish")
    public R<Object> restartpublish(Long sellerStoreProductId) {
        return iErpSellerStoreProductService.restartpublish(sellerStoreProductId);
    }


    /**
     * 发布商品到速卖通
     *
     * @return
     */
    @PostMapping("/push")
    public R<Object> push(Long sellerStoreProductId) {
        return iErpSellerStoreProductService.push(sellerStoreProductId);
    }

    /**
     * 定时任务，用户在店铺中发布商品到速卖通
     *
     * @return
     */
    @GetMapping("/sellerPublishProduct")
    public R<Object> sellerPublishProduct() {
            RLock fairLock = redissonClient.getFairLock(LOCK_TEST_KEY);

        try {
            boolean lock = fairLock.tryLock(5, 10, TimeUnit.MILLISECONDS);
            if (lock) {
                try {
                    // 获取未发布的商品
                    ErpSellerStoreProductExpand expand = erpSellerStoreProductExpandMapper.getUnpublishProduct();
                    if (expand == null) {
                        return R.fail("商品不存在");
                    }
                    expand.setStatus(1); // 发布中
                    erpSellerStoreProductExpandMapper.updateById(expand);

                    iErpSellerStoreProductService.push(expand.getSellerStoreProductId());

                    System.out.println("任务执行完毕");
                } finally {
                    // 只在成功获取锁后解锁
                    fairLock.unlock();
                }
            } else {
                // 锁获取失败，可以在这里处理失败的情况，例如记录日志或执行其他备选逻辑
            }
        } catch (InterruptedException e) {
            // 处理中断异常
            e.printStackTrace();
            // 如果需要，您可能还需要在这里重置中断状态
            // Thread.currentThread().interrupt();
        } catch (Exception e) {
            // 处理其他可能的异常，例如 unlock() 抛出的异常（尽管不太常见）
            e.printStackTrace();
        }

        return R.ok("上架成功");
    }


    @PostMapping("/getSellerStoreProductInfo")
    public R<Object> getSellerStoreProductInfo(@RequestBody ErpSellerStoreProduct erpSellerStoreProduct) {
        return iErpSellerStoreProductService.getSellerStoreProductInfo(erpSellerStoreProduct);
    }

    @PostMapping("/deleteErpSellerStoreProduct")
    public R<Object> deleteErpSellerStoreProduct(@RequestBody ErpSellerStoreProduct erpSellerStoreProduct) {
        return iErpSellerStoreProductService.deleteErpSellerStoreProduct(erpSellerStoreProduct);
    }

    @PostMapping("/publishInnerAuth")
    public R<Object> publishInnerAuth(@RequestBody PublishInnerAuthDto dto) {
        return iErpSellerStoreProductService.publish(
                dto.getSellerProductId().toString(),
                dto.getStoreId(),
                dto.getStock(),
                dto.getErpSellerStoreProductExpand());
    }

    /**
     * 发布商品至速卖通
     *
     * @param sellerStoreProductId
     * @return
     */
    @PostMapping("/pushInnerAuth/{sellerStoreProductId}")
    public R<Object> pushInnerAuth(@PathVariable("sellerStoreProductId") Long sellerStoreProductId) {
        return iErpSellerStoreProductService.push(sellerStoreProductId);
    }

    @GetMapping("/confirmUploadSuccess/{sellerStoreProductId}")
    public R<Object> confirmUploadSuccess(@PathVariable("sellerStoreProductId") Long sellerStoreProductId) {
        iErpSellerStoreProductService.confirmUploadSuccess(sellerStoreProductId);
        return R.ok("确认成功");
    }

    @GetMapping("/selectRepeatProduct/{storeUserName}/{collectProductId}")
    public R<Object> selectRepeatProduct(@PathVariable("storeUserName") String storeUserName, @PathVariable("collectProductId") Long collectProductId) {
        return iErpSellerStoreProductService.selectRepeatProduct(storeUserName, collectProductId);
    }

    /**
     * 根据店铺ID，获取店铺未下架商品数量
     *
     * @param storeId
     * @return
     */
    @GetMapping("/getProductCountByStoreId")
    public R<Object> getProductCountByStoreId(@RequestParam("storeId") String storeId) {
        return R.ok(iErpSellerStoreProductService.selectProductCountByStoreId(Long.parseLong(storeId)));
    }

    @GetMapping("/getProductByCycle/{cycle}/{storeIds}")
    public R<Object> getProductByCycle(@PathVariable("cycle") String cycle, @PathVariable("storeIds") String storeIds) {
        Long[] storeIds_long = StringUtils.convertStringArrayToLongArray(storeIds.split(","));
        List<ErpSellerStoreProduct> list = iErpSellerStoreProductService.queryProductByCycle(Integer.parseInt(cycle), Arrays.asList(storeIds_long));
        if (list != null && list.size() > 0) {
            return R.ok(list);
        }
        return R.ok();
    }
    /**
     * 根据店铺cn码获取第一条产品
     */
    @GetMapping("/getFarthestProduct")
    ErpSellerStoreProduct getFarthestProduct(@RequestParam("storeUserName") String storeUserName) {
        return iErpSellerStoreProductService.getFarthestProduct(storeUserName);
    }

    /**
     * 确认Ae商品信息状态
     *
     * @param
     * @return
     */
    @GetMapping("/confirmAeProductInfoStatus")
    public R<Object> confirmAeProductInfoStatus(String storeUserName) {
        return iErpSellerStoreProductService.confirmAeProductInfoStatus(storeUserName);
    }

    @GetMapping("/confirmAeProductInfoStatusAllStore")
    public R<Object> confirmAeProductInfoStatusAllStore() {
        R<Object> storeObject = remoteAutoSellerStoreService.queryAutoStoreUserName();
        String storeStr =  (String) storeObject.getData();
        List<String> storeList = Arrays.asList(storeStr.split(","));
        for (String storeUserName : storeList) {
            iErpSellerStoreProductService.confirmAeProductInfoStatus(storeUserName);
        }
        return R.ok();
    }


    /**
     * 批量删除产品
     * @param
     * @return
     */
    @GetMapping("/delectBatchProduct")
    public R<Object> delectBatchProducts(Long storeId,Integer type,String storeUserName) {
        return iErpSellerStoreProductService.delectBatchProducts(storeId,type,storeUserName);
    }

}
